package com.ken.producer;

import com.ken.entity.Order;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 生产者
 * Created by renchongyu on 2018/11/26.
 */
@Component
public class RabbitSend {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //回调函数：confirm确认
    final ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback(){
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            System.out.println("correlationData="+correlationData);
            System.out.println("ack="+ack);
            if(!ack){
                System.out.println("异常处理……");
            }
        }
    };

    //回调函数：return确认
    final ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback(){
        @Override
        public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText,
                                    String exchange, String routingKey) {
            System.out.println("replyCode="+replyCode + "| "+"replyText="+replyText+" | exchange="+exchange+" | routingKey="+routingKey);

        }
    };

    //生产者发送一条消息
    public void send(Object object,Map<String,Object> headers){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        MessageHeaders mhs = new MessageHeaders(headers);
        Message msg = MessageBuilder.createMessage(object,mhs);
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnCallback(returnCallback);
        CorrelationData correlationData = new CorrelationData(sdf.format(new Date()));
        rabbitTemplate.convertAndSend("exchange-1","springboot.hello",msg,correlationData);
    }

    //生产者发送一条消息
    public void send(Order order){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnCallback(returnCallback);
        CorrelationData correlationData = new CorrelationData(sdf.format(new Date()));
        rabbitTemplate.convertAndSend("exchange-2","springboot.order",order,correlationData);
    }
}
